#!/usr/bin/python3
"""
OpenCloudOS 9 AI软件验证工具 - 命令行接口
"""

import argparse
import json
import sys
from pathlib import Path
from ai_package_validator import AIPackageValidator


def load_config(config_file: str):
    """加载配置文件"""
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"错误: 配置文件 {config_file} 不存在")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"错误: 配置文件格式错误: {e}")
        sys.exit(1)


def validate_single_package(package_name: str, version: str = None, test_file: str = None, 
                          install_timeout: int = 120, upgrade: bool = False, import_test_timeout: int = 60):
    """验证单个包"""
    validator = AIPackageValidator(default_install_timeout=install_timeout)
    
    package_config = {
        "name": package_name,
        "version": version,
        "install_timeout": install_timeout,
        "import_test_timeout": import_test_timeout,
        "custom_tests": []
    }
    
    # 如果提供了测试文件，读取测试代码
    if test_file and Path(test_file).exists():
        with open(test_file, 'r', encoding='utf-8') as f:
            test_code = f.read()
        package_config["custom_tests"] = [{
            "name": f"custom_test_{package_name}",
            "code": test_code,
            "timeout": 60
        }]
    
    result = validator.validate_package(package_config, upgrade_before_test=upgrade)
    
    print(f"\n=== 验证结果: {package_name} ===")
    if upgrade:
        print(f"升级成功: {'是' if result['upgrade_result'].get('upgrade_success', False) else '否'}")
    print(f"安装成功: {'是' if result['install_result']['install_success'] else '否'}")
    print(f"整体成功: {'是' if result['overall_success'] else '否'}")
    if result.get("timeout_occurred", False):
        print("⚠️  超时发生: 某个步骤超过了时间限制")
    
    if not result['overall_success']:
        if upgrade and not result['upgrade_result'].get('upgrade_success', True):
            print(f"升级错误: {result['upgrade_result']['error_message']}")
        if not result['install_result']['install_success']:
            print(f"安装错误: {result['install_result']['error_message']}")
        
        for test in result['tests']:
            if not test['success']:
                print(f"测试失败 [{test.get('test_name', test['test_type'])}]: {test['error_message']}")


def validate_batch_packages(config_file: str, package_filter: list = None, 
                          install_timeout: int = 120, upgrade: bool = False, import_test_timeout: int = 60):
    """批量验证包"""
    config = load_config(config_file)
    packages = config.get("packages", [])
    
    # 如果指定了包过滤器，只验证指定的包
    if package_filter:
        packages = [pkg for pkg in packages if pkg["name"] in package_filter]
        if not packages:
            print(f"错误: 在配置文件中未找到指定的包: {', '.join(package_filter)}")
            sys.exit(1)
    
    validator = AIPackageValidator(default_install_timeout=install_timeout)
    
    # 为每个包配置超时设置
    for package in packages:
        if "install_timeout" not in package:
            package["install_timeout"] = install_timeout
        if "import_test_timeout" not in package:
            package["import_test_timeout"] = import_test_timeout
    
    result = validator.batch_validate(packages, upgrade_before_test=upgrade)
    
    print("\n=== 批量验证结果汇总 ===")
    print(f"总包数: {result['total_packages']}")
    print(f"成功: {result['successful_packages']}")
    print(f"超时: {result['timeout_packages']}")
    print(f"失败: {result['failed_packages']}")
    print(f"成功率: {result['summary']['success_rate']:.1f}%")
    
    if result['summary']['timeout_packages_list']:
        print(f"\n超时的包:")
        for pkg in result['summary']['timeout_packages_list']:
            print(f"  - {pkg}")
    
    if result['summary']['failed_packages_list']:
        print(f"\n失败的包:")
        for pkg in result['summary']['failed_packages_list']:
            print(f"  - {pkg}")
    
    print(f"\n详细日志已保存到: validation_logs/ 目录")


def list_packages(config_file: str):
    """列出配置文件中的所有包"""
    config = load_config(config_file)
    packages = config.get("packages", [])
    
    print(f"配置文件中的包列表 (共 {len(packages)} 个):")
    print("-" * 60)
    for i, pkg in enumerate(packages, 1):
        version_info = f" (v{pkg['version']})" if pkg.get('version') else " (最新版本)"
        test_count = len(pkg.get('custom_tests', []))
        description = pkg.get('description', '无描述')
        
        print(f"{i:2d}. {pkg['name']}{version_info}")
        print(f"     描述: {description}")
        print(f"     自定义测试: {test_count} 个")
        print()


def main():
    parser = argparse.ArgumentParser(
        description="OpenCloudOS 9 AI软件自动化验证工具",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  # 批量验证所有包
  python3 validate_cli.py batch

  # 使用大型AI包集合进行验证
  python3 validate_cli.py batch --config large_ai_packages_config.json

  # 验证指定的包
  python3 validate_cli.py batch --packages numpy pandas torch

  # 验证前先升级所有包
  python3 validate_cli.py batch --upgrade

  # 设置安装超时时间为180秒
  python3 validate_cli.py batch --install-timeout 180

  # 设置导入测试超时时间为30秒
  python3 validate_cli.py batch --import-test-timeout 30

  # 验证单个包
  python3 validate_cli.py single numpy

  # 验证单个包的特定版本
  python3 validate_cli.py single numpy --version 1.21.0

  # 验证单个包并运行自定义测试
  python3 validate_cli.py single numpy --test-file my_numpy_test.py

  # 列出配置文件中的所有包
  python3 validate_cli.py list
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # 批量验证命令
    batch_parser = subparsers.add_parser('batch', help='批量验证包')
    batch_parser.add_argument(
        '--config', 
        default='packages_config.json',
        help='配置文件路径 (默认: packages_config.json)'
    )
    batch_parser.add_argument(
        '--packages',
        nargs='+',
        help='指定要验证的包名列表 (如果不指定则验证所有包)'
    )
    batch_parser.add_argument(
        '--install-timeout',
        type=int,
        default=120,
        help='安装超时时间（秒）(默认: 120)'
    )
    batch_parser.add_argument(
        '--import-test-timeout',
        type=int,
        default=60,
        help='导入测试超时时间（秒）(默认: 60)'
    )
    batch_parser.add_argument(
        '--upgrade',
        action='store_true',
        help='在验证前升级所有包到最新版本'
    )
    
    # 单包验证命令
    single_parser = subparsers.add_parser('single', help='验证单个包')
    single_parser.add_argument('package', help='包名')
    single_parser.add_argument('--version', help='指定版本')
    single_parser.add_argument('--test-file', help='自定义测试文件路径')
    single_parser.add_argument(
        '--install-timeout',
        type=int,
        default=120,
        help='安装超时时间（秒）(默认: 120)'
    )
    single_parser.add_argument(
        '--import-test-timeout',
        type=int,
        default=60,
        help='导入测试超时时间（秒）(默认: 60)'
    )
    single_parser.add_argument(
        '--upgrade',
        action='store_true',
        help='在验证前升级包到最新版本'
    )
    
    # 列出包命令
    list_parser = subparsers.add_parser('list', help='列出配置文件中的所有包')
    list_parser.add_argument(
        '--config',
        default='packages_config.json', 
        help='配置文件路径 (默认: packages_config.json)'
    )
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    try:
        if args.command == 'batch':
            validate_batch_packages(args.config, args.packages, args.install_timeout, args.upgrade, args.import_test_timeout)
        elif args.command == 'single':
            validate_single_package(args.package, args.version, args.test_file, args.install_timeout, args.upgrade, args.import_test_timeout)
        elif args.command == 'list':
            list_packages(args.config)
    except KeyboardInterrupt:
        print("\n操作已取消")
        sys.exit(1)
    except Exception as e:
        print(f"错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()